<template>
  <div>
    <a-row>
      <a-col :span="14">
        <a-card class="card" title="新增计划、单元和创意数据">
          <a-select v-model="formA.optimizer" @change="AselectChange" style="width: 120px;margin-right:10px;">
            <a-select-option :value="0">
              全部
            </a-select-option>
            <a-select-option :value="item.id" v-for="(item,index) in optimizerList" :key="index">
              {{item.username}}
            </a-select-option> 
          </a-select>
          <a-range-picker
            :ranges="{ '昨天': [moment().add(-1, 'days'), moment().add(-1, 'days')], '过去7天': [moment().add(-7, 'days'), moment().add(-1, 'days')], 
                      '过去30天': [moment().add(-30, 'days'), moment().add(-1, 'days')] }"
            :defaultValue="[moment().add(-30, 'days'), moment().add(-1, 'days')]"
            :disabled-date="disabledDate" @change="formADateChange" style="width:240px;" 
          />
          <div id="chart-mainA" style="width:800px;height:500px"></div>
        </a-card>
      </a-col>  
      <a-col :span="9" :offset="1">
        <a-card class="card" title="总计划数">
          <a-select v-model="formC.optimizer" @change="CselectChange" style="width: 120px;margin-right:10px;">
            <a-select-option :value="0">
              全部
            </a-select-option>
            <a-select-option :value="item.id" v-for="(item,index) in optimizerList" :key="index">
              {{item.username}}
            </a-select-option> 
          </a-select>
          <div id="chart-mainC" style="width:400px;height:500px"></div>
        </a-card>
      </a-col>
    </a-row>
    <a-card class="card" title="消耗、成交额和ROI">
      <a-select v-model="formB.optimizer" @change="BselectChange" style="width: 120px;margin-right:10px;">
        <a-select-option :value="item.id" v-for="(item,index) in optimizerList" :key="index">
          {{item.username}}
        </a-select-option> 
      </a-select>
      <a-range-picker
        :ranges="{ '昨天': [moment().add(-1, 'days'), moment().add(-1, 'days')], '过去7天': [moment().add(-7, 'days'), moment().add(-1, 'days')], 
                  '过去30天': [moment().add(-30, 'days'), moment().add(-1, 'days')] }"
        :defaultValue="[moment().add(-30, 'days'), moment().add(-1, 'days')]"
        :disabled-date="disabledDate" @change="formBDateChange" style="width:240px;" 
      />
      <div style="display:flex;">
        <div id="chart-mainB" style="width:600px;height:500px;margin-right:20px;"></div>
        <div id="chart-mainB2" style="width:600px;height:500px;margin-right:20px;"></div> 
        <div id="chart-mainB3" style="width:300px;height:500px;margin-right:20px;"></div> 
      </div>
    </a-card>
  </div>
</template>

<script>
import {getNewByOptimizer, getSummaryByOptimizer, getCampaignCounts} from '@/api/shuju/shuju'
import {getOptimizerList} from '@/api/xinxiliu/account'
import moment from 'moment';
import * as echarts from 'echarts';

export default {
  data(){
    return{
      moment,
      formA:{
        start_date: moment().add(-30, 'days').format("YYYY-MM-DD"),
        end_date: moment().add(-1, 'days').format("YYYY-MM-DD"),
        optimizer: 0,
      },
      formB:{
        start_date: moment().add(-30, 'days').format("YYYY-MM-DD"),
        end_date: moment().add(-1, 'days').format("YYYY-MM-DD"),
        optimizer: '',
      },
      formC:{
        optimizer:0,
      },
      Adata:{
        addAdgroupFeed: 0,
        addCampaignFeed: 0,
        addCreativeFeed: 0,
      },
      Bdata:{
        ROI:0,
        cost:0, //总消费
        ctProductPaySuccess: 0, // 成单
        ctProductPaySuccessAmount: 0, // 成单金额
        successAmount:0, //总成交额
        liveOrderData:{
          cost:0,
          liveOrderConversions:0,
          liveOrderAmountConversions: 0
        }
      },
      Cdata:{
        counts: 0
      },
      optimizerList:[],
      Achart:'',
      Bchart:'',
      Bchart2:'',
      B3chart:'',
      Cchart:'',
    }
  },
  created(){
    this.init()
  },
  mounted(){
    this.createChart()
  },
  methods:{
    init(){
      this.getOptimizerList()
      this.getNewByOptimizer()
      this.getCampaignCounts()
    },
    getNewByOptimizer(){
      let formA = JSON.parse(JSON.stringify(this.formA))
      if(formA.optimizer == 0){
        delete formA.optimizer
      }
      if(formA.start_date == '' || formA.end_date == ''){
        delete formA.start_date
        delete formA.end_date
      }
      getNewByOptimizer(formA).then((res) => {
        console.log(res)
        if(res.errcode == 0){
          this.Adata = res.data
          this.setAChartOptions()
        }
      }).catch(() => {
        
      });
    },
    getSummaryByOptimizer(){
      let formB = JSON.parse(JSON.stringify(this.formB))
      if(formB.optimizer == 0){
        delete formB.optimizer
      }
      if(formB.start_date == '' || formB.end_date == ''){
        delete formB.start_date
        delete formB.end_date
      }
      getSummaryByOptimizer(formB).then((res) => {
        console.log(res)
        if(res.errcode == 0){
          let Bdata = {
            liveOrderData:{}
          }
          Bdata.ROI = res.data.ROI || 0,
          Bdata.cost = res.data.cost || 0, //总消费
          Bdata.ctProductPaySuccess = parseInt(res.data.ctProductPaySuccess || 0), // 成单
          Bdata.ctProductPaySuccessAmount = res.data.ctProductPaySuccessAmount || 0, // 成单金额
          Bdata.liveOrderData.cost = res.data.liveOrderData.cost || 0,
          Bdata.liveOrderData.liveOrderConversions = parseInt(res.data.liveOrderData.liveOrderConversions || 0),
          Bdata.liveOrderData.liveOrderAmountConversions = res.data.liveOrderData.liveOrderAmountConversions || 0,
          Bdata.successAmount = res.data.successAmount || 0
          Bdata.ROI = Bdata.ROI.toFixed(2)
          Bdata.cost = Bdata.cost.toFixed(2)
          Bdata.liveOrderData.cost = Bdata.liveOrderData.cost.toFixed(2)
          console.log(Bdata)
          this.Bdata = Bdata
          this.setBChartOptions()
        }
      }).catch(() => {
        
      });
    },
    getCampaignCounts(){
      let formC = JSON.parse(JSON.stringify(this.formC))
      if(formC.optimizer == 0){
        delete formC.optimizer
      }
      getCampaignCounts(formC).then((res) => {
        console.log(res)
        if(res.errcode == 0){
          this.Cdata = res.data
          this.setCChartOptions()
        }
      }).catch(() => {
        
      });
    },
    getOptimizerList(){
      getOptimizerList({}).then((res) => {
        console.log(res)
        if(res.errcode == 0){
          this.optimizerList = res.data
          if(res.data.length > 0){
            this.formB.optimizer = res.data[0].id
            this.getSummaryByOptimizer()
          }
        }
      }).catch(() => {
        
      })
    },
    setAChartOptions(){
      let xAxisArr = ['计划数量', '单元数量', '创意数量']
      let seriesArr = [this.Adata.addAdgroupFeed, this.Adata.addCampaignFeed, this.Adata.addCreativeFeed]
      const options = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisArr,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {  
            interval: 0,  
            formatter: function (value) {
              var ret = "";
              var maxLength = 10;
              var valLength = value.length;
              var rowN = Math.ceil(valLength / maxLength);
              if (rowN > 1) {
                for (var i = 0; i < rowN; i++) {
                  temp = "";
                  var start = i * maxLength;
                  var end = start + maxLength;
                  var temp = value.substring(start, end) + "\n";
                  ret += temp;
                }
                return ret;
              } else {
                return value;
              }
            },
          },
          // axisLabel: { interval: 0, rotate: -20 }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesArr,
            type: 'bar'
          }
        ]
      }
      this.Achart.hideLoading()
      this.Achart.setOption(options)
    },
    setBChartOptions(){
      let xAxisArr = ['总消费','直播间消费']
      let seriesArr = [this.Bdata.cost, this.Bdata.liveOrderData.cost]
      let xAxisArr2 = ['总成交额','基木鱼成交额','直播间成交额']
      let seriesArr2 = [this.Bdata.successAmount, this.Bdata.ctProductPaySuccessAmount, this.Bdata.liveOrderData.liveOrderAmountConversions]
      let xAxisArr3 = ['ROI']
      let seriesArr3 = [this.Bdata.ROI]
      const options = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisArr,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {  
            interval: 0,  
            formatter: function (value) {
              var ret = "";
              var maxLength = 10;
              var valLength = value.length;
              var rowN = Math.ceil(valLength / maxLength);
              if (rowN > 1) {
                for (var i = 0; i < rowN; i++) {
                  temp = "";
                  var start = i * maxLength;
                  var end = start + maxLength;
                  var temp = value.substring(start, end) + "\n";
                  ret += temp;
                }
                return ret;
              } else {
                return value;
              }
            },
          },
          // axisLabel: { interval: 0, rotate: -20 }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesArr,
            type: 'bar'
          }
        ]
      }
      const options2 = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisArr2,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {  
            interval: 0,  
            formatter: function (value) {
              var ret = "";
              var maxLength = 10;
              var valLength = value.length;
              var rowN = Math.ceil(valLength / maxLength);
              if (rowN > 1) {
                for (var i = 0; i < rowN; i++) {
                  temp = "";
                  var start = i * maxLength;
                  var end = start + maxLength;
                  var temp = value.substring(start, end) + "\n";
                  ret += temp;
                }
                return ret;
              } else {
                return value;
              }
            },
          },
          // axisLabel: { interval: 0, rotate: -20 }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesArr2,
            type: 'bar'
          }
        ]
      }
      const options3 = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisArr3,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {  
            interval: 0,  
            formatter: function (value) {
              var ret = "";
              var maxLength = 10;
              var valLength = value.length;
              var rowN = Math.ceil(valLength / maxLength);
              if (rowN > 1) {
                for (var i = 0; i < rowN; i++) {
                  temp = "";
                  var start = i * maxLength;
                  var end = start + maxLength;
                  var temp = value.substring(start, end) + "\n";
                  ret += temp;
                }
                return ret;
              } else {
                return value;
              }
            },
          },
          // axisLabel: { interval: 0, rotate: -20 }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesArr3,
            type: 'bar'
          }
        ]
      }
      this.Bchart.hideLoading()
      this.Bchart.setOption(options)
      this.B2chart.hideLoading()
      this.B2chart.setOption(options2)
      this.B3chart.hideLoading()
      this.B3chart.setOption(options3)
    },
    setCChartOptions(){
      let xAxisArr = ['计划数量']
      let seriesArr = [this.Cdata.counts]
      const options = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisArr,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {  
            interval: 0,  
            formatter: function (value) {
              var ret = "";
              var maxLength = 10;
              var valLength = value.length;
              var rowN = Math.ceil(valLength / maxLength);
              if (rowN > 1) {
                for (var i = 0; i < rowN; i++) {
                  temp = "";
                  var start = i * maxLength;
                  var end = start + maxLength;
                  var temp = value.substring(start, end) + "\n";
                  ret += temp;
                }
                return ret;
              } else {
                return value;
              }
            },
          },
          // axisLabel: { interval: 0, rotate: -20 }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesArr,
            type: 'bar'
          }
        ]
      }
      this.Cchart.hideLoading()
      this.Cchart.setOption(options)
    },
    createChart(){
      this.Achart = echarts.init(document.getElementById('chart-mainA'));
      this.Achart.showLoading({
        text: 'loading',
      });

      this.Bchart = echarts.init(document.getElementById('chart-mainB'));
      this.Bchart.showLoading({
        text: 'loading',
      });
      this.B2chart = echarts.init(document.getElementById('chart-mainB2'));
      this.B2chart.showLoading({
        text: 'loading',
      });
      this.B3chart = echarts.init(document.getElementById('chart-mainB3'));
      this.B3chart.showLoading({
        text: 'loading',
      });

      this.Cchart = echarts.init(document.getElementById('chart-mainC'));
      this.Cchart.showLoading({
        text: 'loading',
      });
    },
    AselectChange(){
      this.getNewByOptimizer()
    },
    BselectChange(){
      this.getSummaryByOptimizer()
    },
    CselectChange(){
      this.getCampaignCounts()
    },
    formADateChange(e){
      this.formA.start_date = e[0].format("YYYY-MM-DD")
      this.formA.end_date = e[1].format("YYYY-MM-DD")
      console.log(this.formA)
      this.getNewByOptimizer()
    },
    formBDateChange(e){
      this.formB.start_date = e[0].format("YYYY-MM-DD")
      this.formB.end_date = e[1].format("YYYY-MM-DD")
      console.log(this.formB)
      this.getSummaryByOptimizer()
    },
    disabledDate(current){
      return current && current > moment().endOf('day').add(-1, 'days');
    }
  }
}
</script>

<style lang="less" scoped>
.card{
  margin-bottom: 20px;
}
</style>